package app.base.common;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import app.base.systemmanage.systemrolespermsmanage.dao.SysRolesPermsMappingDAO;

import app.base.systemmanage.systemrolespermsmanage.model.SysRolesPermsMappingExample;
import app.base.systemmanage.systemrolespermsmanage.model.SysRolesPermsMappingExample.Criteria;

import app.base.systemmanage.systemusersmanage.dao.SysUsersDAO;

import app.base.systemmanage.systemusersrolesmanage.dao.SysUsersRolesMappingDAO;

public class UserSessionInfo {
	private String loginId;
	private String userId;
	private String[] userRoles;
	private String[] userPerms;
	
	public void setLoginId(String loginId)
	{
		this.loginId = loginId;
	}
	
	public String getLoginId()
	{
		return this.loginId;
	}
	
	public void setUserId(String userId)
	{
		this.userId = userId;
	}
	
	public String getUserId()
	{
		return this.userId;
	}
	
	public void setUserRoles(String[] userRoles)
	{
		this.userRoles = userRoles;
	}
	
	public String[] getUserRoles()
	{
		return this.userRoles;
	}
	
	public void setUserPerms(String[] userPerms)
	{
		this.userPerms = userPerms; 
	}
	
	public String[] getUserPerms()
	{
		return this.userPerms;
	}
	
	@SuppressWarnings("unchecked")
	public static String[] getUserRoles(String userId)
	{
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysUsersRolesMappingDAO sysUsersRolesMappingDAO = (SysUsersRolesMappingDAO)context.getBean(Utility.SYSTEM_USERS_ROLES_MAPPING_MANAGE_MODULE_BEAN_NAME);
	   
		Map<String, Object>  map = new HashMap<String, Object>();
		
		map.put("userId", userId);
		
		List list = sysUsersRolesMappingDAO.select_0002(map);	
		
		StringBuffer roleIds = new StringBuffer("");
		
		for(int index = 0; index < list.size(); index++)
		{
			Map resultMap = (Map) list.get(index);

			roleIds.append(resultMap.get("ROLE_ID").toString().trim());
            
            if (index < list.size() - 1) {
            	roleIds.append(Utility.SPLIT_CHARS_VERTICAL_LINE);
            }
		}		
		
		StringTokenizer strTokenizer = new StringTokenizer(roleIds.toString(), Utility.SPLIT_CHARS_VERTICAL_LINE);   
		
		String[] userRoles = new String[strTokenizer.countTokens()]; 
		int index = 0;
		
		while(strTokenizer.hasMoreTokens()) {   
			userRoles[index++] = strTokenizer.nextToken();   
		}  	
		
		return userRoles;
	}
	
	@SuppressWarnings("unchecked")
	public static String[] getUserPerms(String userId)
	{
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysRolesPermsMappingDAO sysRolesPermsMappingDAO = (SysRolesPermsMappingDAO)context.getBean(Utility.SYSTEM_ROLES_PERMS_MAPPING_MANAGE_MODULE_BEAN_NAME);
								
		SysRolesPermsMappingExample example = new SysRolesPermsMappingExample();
		
		Criteria criteria = example.createCriteria();
		
		String[] userRoles = getUserRoles(userId);
		String[] userPerms = new String[0];
		
		if (!(userRoles == null || userRoles.length == 0)) {
			List<String> roleIds = new ArrayList<String>(); 
			roleIds = Arrays.asList(userRoles);
			
			criteria.andROLE_IDIn(roleIds);
			
			List list = sysRolesPermsMappingDAO.select_0002(example);
			
			///////////////////////////////////////////////
			//!!!!!!!!!!这里需要修改成直接用List迭代器
			StringBuffer permIds = new StringBuffer("");
			
			for(int index = 0; index < list.size(); index++)
			{
				Map resultMap = (Map) list.get(index);
				
				permIds.append(resultMap.get("PERM_CODE").toString().trim());
	            
	            if (index < list.size() - 1) {
	            	permIds.append(Utility.SPLIT_CHARS_VERTICAL_LINE);
	            }
			}
			
			StringTokenizer strTokenizer = new StringTokenizer(permIds.toString(), Utility.SPLIT_CHARS_VERTICAL_LINE);   
			
			userPerms = new String[strTokenizer.countTokens()]; 
			int index = 0;
			
			while(strTokenizer.hasMoreTokens()) {   
				userPerms[index++] = strTokenizer.nextToken();   
			} 
			///////////////////////////////////////////////
		}
		return userPerms;		
	}
	
	@SuppressWarnings("unchecked")
	public static String getUserId(String loginId)
	{
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysUsersDAO sysUsersDAO = (SysUsersDAO)context.getBean(Utility.SYSTEM_USERS_MANAGE_MODULE_BEAN_NAME);
	    
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("loginId", loginId);
		
		List list = sysUsersDAO.select_0002(map);	
		
		return (list.size() > 0) ? ((Map) list.get(0)).get("USER_ID").toString().trim() : null;
	}
	
	public static boolean verifyUserPerms(HttpSession session, String[] perms)
	{		
		//String[] p = getUserPerms(getUserId(((UserSessionInfo) session.getAttribute(Utility.LOGIN_USER_SESSION_INFO)).getLoginId()));
		String[] p = ((UserSessionInfo) session.getAttribute(Utility.LOGIN_USER_SESSION_INFO)).getUserPerms();
		
		for (int i = 0; i < p.length; i++)
		{
			for (int j = 0; j < perms.length; j++)
			{
				if (perms[j].trim().equals(p[i].trim()))
				{
					return true;
				}
				
			}			
		}
		return false;
	}
	
	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 * @throws NoSuchAlgorithmException 
	 */
	public static void main(String[] args) 
		throws NoSuchAlgorithmException, UnsupportedEncodingException 
	{
		// TODO Auto-generated method stub
		//UserSessionInfo.getUserRoles("SYSUSERID20090831000000363");
		//UserSessionInfo.getUserId("admin");
		/*String[] userPerms = UserSessionInfo.getUserPerms(getUserId("root"));
		
		for (int i = 0; i < userPerms.length; i++)
		{
			System.out.println(userPerms[i]);
		}*/
		

		
	}

}
